package cs2340.spring13.team3.wheresmystuff.views;

import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import cs2340.spring13.team3.wheresmystuff.R;
import cs2340.spring13.team3.wheresmystuff.presenters.LoginManager;

/**
 * @author R Keane, I Stainbrook
 * 
 *         Activity which displays a login screen to the user, offering
 *         registration as well.
 */
public class CreateAccountActivity extends Activity implements ILoginView {
	private UserRegisterTask mRegTask = null;
	private LoginManager myLoginManager;
	private Intent i;
	private EditText mEmailView, mPasswordView;

	// TODO: Fix creating account with same name as existing...

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_create_account);
		myLoginManager = LoginManager.getInstance();

		mEmailView = (EditText) findViewById(R.id.createAcctEmail);
		mPasswordView = (EditText) findViewById(R.id.createAcctPassword);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.login, menu);
		return true;
	}

	/**
	 * Uses the LoginManager (presenter) to attempt to register a new user with
	 * the credentials in the text fields when the corresponding button is
	 * clicked
	 * 
	 * @param source
	 *            The button from which the click originates
	 */

	public void onRegisterClick(View source) {
		if (mRegTask != null) {
			return;
		}
		if (!getPasswordField().getText().toString()
				.equals(getConfirmPasswordField().getText().toString())) {
			getConfirmPasswordField().setError("Password fields do not match");
			// displayLoginMessage("Registration Failed", "Error: "
			// + getConfirmPasswordField().getError());
			return;
		} else if (checkInvalidEmail(getEmailField().getText().toString())) {
			// displayLoginMessage("Registration Failed", "Error: "
			// + getEmailField().getError());
			return;
		} else if (checkInvalidPassword(getPasswordField().getText().toString())) {
			// displayLoginMessage("Registration Failed", "Error: "
			// + getPasswordField().getError());
			return;
		} else {
			i = new Intent();
			i.putExtra("email", getEmailField().getText().toString());
			i.putExtra("password", getPasswordField().getText().toString());
			mRegTask = new UserRegisterTask(this, getEmailField().getText()
					.toString(), getPasswordField().getText().toString());
			mRegTask.execute((Void) null);

		}
	}

	/**
	 * Check the validity of the user-inputed email
	 * 
	 * @param email
	 *            string to validate
	 * @return whether or not the email is valid according to our incorrect
	 *         regex
	 */
	public boolean checkInvalidEmail(String email) {
		mEmailView.setError(null);
		if (TextUtils.isEmpty(email)) {
			mEmailView.setError("Field is required");
			return true;
		} else if (!email.matches("[a-zA-Z_0-9.]+@[a-zA-Z_0-9.]+.[a-zA-Z]{3}")) {
			mEmailView.setError("Invalid email");
			return true;
		}
		return false;
	}

	/**
	 * Check the validity of the user-inputed password
	 * 
	 * @param password
	 *            string to check
	 * @return whether or not the password is valid (length > 3 characters)
	 */
	public boolean checkInvalidPassword(String password) {
		mPasswordView.setError(null);
		if (TextUtils.isEmpty(password)) {
			mPasswordView.setError("Field is required");
			return true;
		} else if (password.length() < 4) {
			mPasswordView.setError("Password too short");
			return true;
		}
		return false;
	}

	/**
	 * Closes the activity when the user hits cancel, returning to the login
	 * activity
	 * 
	 * @param source
	 *            The button from which the click originates
	 */
	public void onCancelClick(View source) {
		setResult(-1, new Intent());
		finish();
	}

	/**
	 * Uses a simple AlertDialog to display a message to the end user regarding
	 * the operations of the program lets them know about errors, or the success
	 * of the account creation
	 * 
	 * @param message
	 *            The message to display
	 */

	@Override
	public void displayLoginMessage(String title, String message) {
		AlertDialog alertDialog = new AlertDialog.Builder(
				getApplicationContext()).create();
		alertDialog.setMessage(message);
		alertDialog.show();
	}

	/**
	 * Returns the text field used to input an email address
	 * 
	 * @return The email text field
	 */

	private EditText getEmailField() {
		return (EditText) findViewById(R.id.createAcctEmail);
	}

	/**
	 * Returns the text field used to input a password
	 * 
	 * @return The password text field
	 */

	private EditText getPasswordField() {
		return (EditText) findViewById(R.id.createAcctPassword);
	}

	/**
	 * Returns the text field used to input the password a second time (for
	 * confirmation)
	 * 
	 * @return The password text field
	 */

	private EditText getConfirmPasswordField() {
		return (EditText) findViewById(R.id.createAcctPasswordRepeat);
	}

	public class UserRegisterTask extends AsyncTask<Void, Void, Boolean> {
		@SuppressWarnings("unused")
		private Activity activity;
		private String email, password;

		public UserRegisterTask(Activity applicationActivity, String email,
				String pass) {
			this.activity = applicationActivity;
			this.email = email;
			this.password = pass;
		}

		@Override
		protected Boolean doInBackground(Void... params) {
			try {
				return myLoginManager
						.attemptRegister(this.email, this.password);
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
		}

		@Override
		protected void onPostExecute(final Boolean success) {
			mRegTask = null;

			if (success) {
				setResult(100, i);
				finish();
			} else {
				displayLoginMessage("Registration Failed", "Please try again.");
			}
		}

	}

}
